<template>
  <div>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchList">
          <a-row :gutter="48">
            <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
              <a-form-item label="活动名称">
                <a-input v-model="queryParam.activityName" />
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
              <a-form-item label="参与活动品牌">
                <a-select v-model="queryParam.joinBrandId" show-search :filter-option="filterOption">
                  <a-select-option value="">不限</a-select-option>
                  <a-select-option :value="item.value" v-for="item in brandsList" :key="item.value">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
              <a-form-item label="创建日期">
                <a-range-picker style="width:100%;" format="YYYY-MM-DD" :placeholder="['开始时间', '结束时间']" v-model="queryParam.timePicker" />
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :xl="8" :lg="12" :sm="24">
              <a-form-item label="首页展示">
                <a-select v-model="queryParam.miniAppShow">
                  <a-select-option value="">不限</a-select-option>
                  <a-select-option :value="1">展示</a-select-option>
                  <a-select-option :value="0">隐藏</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xxl="24" :xl="16" :lg="24" :sm="24">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-button type="primary" @click="searchList">查询</a-button>
                <a-button style="margin-left: 18px" @click="resetList">重置</a-button>
                <a-button style="margin-left: 18px" type="primary" icon="plus" @click="handleAdd">新建</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-tabs :activeKey="queryParam.status" @change="tabsChange">
        <a-tab-pane :key="1" :tab="`进行中（${running}）`"></a-tab-pane>
        <a-tab-pane :key="0" :tab="`未开始（${wait}）`" forceRender></a-tab-pane>
        <a-tab-pane :key="2" :tab="'已结束'" forceRender></a-tab-pane>
      </a-tabs>
      <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps">
        <span slot="coverPicture" slot-scope="text">
          <img :src="text" alt="" class="thumbnail" @click="handleShowImg(text)" />
        </span>
        <span slot="activityName" slot-scope="text">
          <ellipsis :length="18" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="action" slot-scope="text, record" style="line-height:28px;">
          <template>
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleLookList(record)">主题搭配列表</a>
            <br />
            <a-popconfirm :title="`确定${queryParam.status == 1 ? '结束' : '开始'}该主题搭配活动吗?`" ok-text="确定" cancel-text="取消" @confirm="confirm(record)">
              <a v-show="queryParam.status == 0">上线</a>
              <a v-show="queryParam.status == 1">下线</a>
            </a-popconfirm>
            <a-divider type="vertical" v-show="queryParam.status != 2" />
            <a v-show="queryParam.status != 2" @click="getQrCode(record)">
              二维码
            </a>
          </template>
        </span>
      </s-table>
    </a-card>
    <a-modal v-model="showVisible" width="600px" :footer="null" title="封面图" @cancel="showVisible = false"> <img class="show-img" :src="showImg" alt="" /> </a-modal>
    <CodeModal ref="codeModal"></CodeModal>
  </div>
</template>
<script>
import { STable, Ellipsis } from '../../components'
import { routeMixin } from '@/views/box/util/routeMixin'
import { themeMixin } from './util/mixin'
import CodeModal from './codeModal'
import { getThemeActivityList, createThemeActivityQrCode, upOrDownThemeActivityById } from '@/api/box/theme'
const columns = [
  {
    title: '封面图',
    dataIndex: 'coverPicture',
    scopedSlots: { customRender: 'coverPicture' }
  },
  {
    title: '活动名称',
    dataIndex: 'activityName',
    align: 'center',
    scopedSlots: { customRender: 'activityName' }
  },
  {
    title: '参与活动品牌',
    dataIndex: 'joinBrandName',
    align: 'center',
    scopedSlots: { customRender: 'joinBrandName' }
  },
  {
    title: '活动时间',
    dataIndex: 'startTime',
    align: 'center',
    customRender: (text, record) => `${text} ~ ${record.endTime}`
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '200px',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  0: {
    status: 'error',
    text: '禁用'
  },
  1: {
    status: 'success',
    text: '启用'
  }
}
export default {
  mixins: [routeMixin, themeMixin],
  components: {
    STable,
    Ellipsis,
    CodeModal
  },
  data() {
    this.columns = columns
    return {
      // 查询参数
      queryParam: {
        status: 1,
        joinBrandId: ''
      },
      wait: '',
      running: '',
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
        /* itemRender: (current, type, originalElement) => {
          if (type === 'prev') {
            return <a>上一页</a>
          } else if (type === 'next') {
            return <a>下一页</a>
          }
          return originalElement
        } */
      },
      loadData: parameter => this.fetchList(parameter),
      showVisible: false,
      showImg: ''
    }
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    }
  },
  watch: {
    $route(to, from) {
      if (this.siblingNameList.includes(from.name) && to.path === this.currentPath) {
        console.log('******refresh ThemeList*******')
        this.$refs.table.refresh()
      } else if (this.siblingNameList.includes(to.name) && from.path == this.currentPath) {
      } else if (to.path === this.currentPath && !this.siblingNameList.includes(from.name)) {
        /*  console.log('******destroy ThemeList*******')
        this.$destroy() */
        this.resetList()
      }
    }
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    filterFields(values) {
      const formValue = {}
      Object.keys(values).forEach(i => {
        if (values[i] !== '' && values[i] !== undefined) {
          if (i === 'timePicker') {
            if (values[i].length) {
              formValue.createStartTime = values[i][0].format('YYYY-MM-DD')
              formValue.createEndTime = values[i][1].format('YYYY-MM-DD')
            }
          } else {
            formValue[i] = values[i]
          }
        }
      })
      return formValue
    },
    fetchList(parameter) {
      let formValue = this.filterFields(this.queryParam)
      let params = {
        page: parameter,
        requestData: {
          status: this.queryParam.status,
          ...formValue
        }
      }
      return getThemeActivityList(params).then(res => {
        if (res.code == 0) {
          this.running = res.data.running
          this.wait = res.data.wait
          let result = {
            data: res.data.data,
            page: res.page
          }
          return result
        } else {
          this.$message.warning(res.msg)
          const data = {
            page: {
              pageNo: 0,
              count: 0,
              pageSize: 10
            },
            data: []
          }
          return data
        }
      })
    },
    tabsChange(key) {
      this.queryParam.status = key
      this.$refs.table.refresh(true)
    },
    searchList() {
      this.$refs.table.refresh(true)
    },
    resetList() {
      this.queryParam = {
        status: 1,
        joinBrandId: ''
      }
      this.$refs.table.refresh(true)
    },
    handleAdd() {
      this.$router.push('/box/operations/theme/themeDetail/add')
    },
    handleEdit(record) {
      this.$router.push(`/box/operations/theme/themeDetail/${record.id}`)
    },
    handleLookList(record) {
      this.$router.push(`/box/operations/theme/lookList/${record.id}`)
    },
    handleShowImg(url) {
      this.showImg = url
      this.showVisible = true
    },
    getQrCode(record) {
      let params = {
        requestData: {
          themeActivityId: record.id,
          materialId: record.materialId
        }
      }
      createThemeActivityQrCode(params).then(res => {
        if (res.code == 0) {
          this.$refs.codeModal.show(res.data)
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    confirm(record) {
      console.log(this.queryParam.status)
      let params = {
        requestData: {
          id: record.id,
          status: this.queryParam.status == 0 ? 0 : 1
        }
      }
      upOrDownThemeActivityById(params).then(res => {
        if (res.code == 0) {
          this.$message.success('修改成功！')
          this.$refs.table.refresh()
        } else {
          this.$message.warning(res.msg)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.thumbnail {
  width: 60px;
  height: 60px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
  cursor: pointer;
}
.show-img {
  display: block;
  width: 100%;
}
</style>

